package com.jml.proxy;

import com.jml.config.JmlFeignConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class JmlInvocationHandler implements InvocationHandler, ApplicationContextAware {

    private ApplicationContext context;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 判断 tClass  属于那个包  根据包的名称获取 服务的名称
        // 2.获取服务的名称 获取该接口的包名
        String classAddresName = method.getDeclaringClass().getName();
        String pkName = classAddresName.substring(0, classAddresName.lastIndexOf("."));
        JmlFeignConfig jmlFeignConfig = context.getBean("jmlFeignConfig", JmlFeignConfig.class);
        //根据包名，获取服务名字(根据配置文件获得)，也可以根据注解中的内容获取服务名字，这里没写注解的属性
        String serviceName = jmlFeignConfig.getFeignService().get(pkName);
        if (StringUtils.isEmpty(serviceName)) {
            throw new Exception("serviceName is null");
        }
        // 3.接口地址如何获取？
        GetMapping getMapping = method.getDeclaredAnnotation(GetMapping.class);
        if (getMapping == null) {
            throw new Exception("getMapping is null");
        }
        String[] requestName = getMapping.value();
        String requestUrl = "http://" + serviceName + requestName[0];
        RestTemplate restTemplate = this.context.getBean("restTemplate", RestTemplate.class);
        ResponseEntity<?> result = restTemplate.getForEntity(requestUrl, method.getReturnType());
        return result.getBody();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static void main(String[] args) {
        String pk = "com.jml.service.MemberService";
        String substring = pk.substring(0, pk.lastIndexOf("."));
        System.out.println(substring);
    }
}
